package org.shj.book2.chapter06.improve;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * JDK 提供了Read-Writer Lock 的实现
 * @author huangjian
 *
 */
public class Main {

	public static void main(String[] args){
		
		Data data = new Data(10);
		
		List<ReaderThread> list = new ArrayList<ReaderThread>();
		for(int i = 0 ; i < 6; i++){
			ReaderThread thread = new ReaderThread(data);
			thread.start();
			list.add(thread);
		}
		
		CyclicBarrier barrier = new CyclicBarrier(3);
		
		new WriterThread(data, barrier, "ABCDEFGHIJKLMNOPQRSTUVWXYZ").start();
		new WriterThread(data, barrier, "abcdefghijklmnopqrstuvwxyz").start();
		
		try{
			Thread.sleep(1000); //let the other thread start
		}catch(Exception e){
			
		}
		
		long begin = System.currentTimeMillis();
		
		try {
			barrier.await();
		} catch (InterruptedException | BrokenBarrierException e) {
			e.printStackTrace();
		}
		
		System.out.println(System.currentTimeMillis() - begin);
		for(ReaderThread thread : list){
			thread.terminate();
		}		
	}
}
